<template>
    <!-- 收货地址 -->
    <van-contact-card type="edit" :name="`${address.name} ${address.region_text}`" :tel="address.tel" v-if="Object.getOwnPropertyNames(address).length > 0" @click="AddressSelect = true" />
    <van-contact-card type="add" v-else @click="AddressShow = true" />

    <!-- 收货地址添加弹出框 -->
    <van-popup
        v-model:show="AddressShow"
        position="bottom"
        round
    >
        <van-address-edit
            show-set-default
            :area-list="areaList"
            :area-columns-placeholder="['请选择', '请选择', '请选择']"
            :address-info="AddressInfo"
            @save="OnAddressAdd"
        />
    </van-popup>

    <!-- 收货地址选择弹出框 -->
    <van-popup
        v-model:show="AddressSelect"
        position="bottom"
        round
    >
        <van-address-list 
            v-model="AddressActive"
            :list="AddressList"
            default-tag-text="默认"
            :show-add-button="false"
            @select="OnAddressSelect"
        />
    </van-popup>

    <!-- 商品卡片 -->
    <van-card
        v-for="(item, key) in CartList"
        :thumb="item.product.thumb_text"
        :num="item.nums"
        :key="item.id"
    >
        <template #title>
            <div class="title">{{item.product.name}}</div>
        </template>

        <!-- 规格 -->
        <template #desc v-if="item.attrs">
            <van-tag v-for="(attr, index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
            <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
        </template>
        <template #desc v-else>
            <van-tag class="tag" type="primary">无规格数据</van-tag>
            <van-tag class="tag" type="warning" v-if="item.type === 'live'">直播商品</van-tag>
        </template>

        <template #price>
            <div class="price">单价：￥{{item.price}}</div>
            <div class="price">合计：￥{{item.total}}</div>
        </template>
    </van-card>

    <!-- 支付方式 -->
    <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true"></van-cell>

    <!-- 支付方式的选择器 -->
    <van-popup
        v-model:show="PayShow"
        position="bottom"
        round
    >
        <van-picker 
            title="请选择支付方式"
            :columns="PayList"
            @cancel="PayShow = false"
            @confirm="OnPayConfirm"
        />

    </van-popup>

    <!-- 优惠券单元格 -->
    <!-- coupons 可选的优惠券 -->
    <!-- chosen-coupon 当前已选的优惠券 -->
    <van-coupon-cell
        :coupons="CouponList"
        :chosen-coupon="CouponActive"
        @click="CouponShow = true"
    />

    <!-- 优惠券列表 -->
    <van-popup
        v-model:show="CouponShow"
        position="bottom"
        round
        style="height: 90%; padding-top: 4px;"
    >
        <van-coupon-list 
            :coupons="CouponList"
            :disabled-coupons="NotCouponList"
            :chosen-coupon="CouponActive"
            :exchange-button-disabled="true"
            :show-exchange-bar="false"
            @change="OnCouponChange"
        />
    </van-popup>

    <!-- 订单备注 -->
    <van-field 
        v-model="remark"
        rows="2"
        autosize
        label="订单备注"
        type="textarea"
        maxlength="120"
        placeholder="请输入订单备注"
        show-word-limit
    />

    <!-- 提交动作栏 -->
    <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="OnSubmit" />
</template>

<script setup>
    // 引入地区数据
    import { areaList } from '@vant/area-data';

    const {proxy} = getCurrentInstance()

    let cartids = ref(proxy.$route.query.cartids ?? 0)
    let business = proxy.$business
    let CartList = ref([])
    let remark = ref('')

    // 支付方式
    const PayShow = ref(false);
    const PayActive = ref({text: '余额支付', value: 'money'});
    const PayList = ref([
        {text: '余额支付', value: 'money'},
        {text: '微信支付', value: 'wx'},
        {text: '支付宝支付', value: 'zfb'},
    ])

    // 优惠券
    const CouponList = ref([]); //列表
    const NotCouponList = ref([]); //不可用的
    const CouponShow = ref(false); //是否显示
    const CouponActive = ref(-1); //当前选中的优惠券

    const address = ref({});
    const AddressInfo = ref({});
    const AddressShow = ref(false);
    const AddressSelect = ref(false);
    const AddressList = ref([]);
    const AddressActive =ref(0)

    onBeforeMount(() => {
        GetCartData()
        GetCouponData()
        GetAddressData()
        GetAddressList()

        //设置添加收货地址的默认信息
        AddressInfo.value = {
            name: business.value.nickname,
            tel: business.value.mobile,
            areaCode: business.value.district || business.value.city || business.value.province,
        }
    })

    //计算优惠后的总价格
    const total = computed(() => {
        let total = 0;
        
        //获取总价
        CartList.value.map((item) => total += parseFloat(item.total));

        // 有选择优惠券
        if(CouponActive.value != -1)
        {
            let rate = CouponList.value[CouponActive.value].rate;

            total = (total * rate).toFixed(2);
        }

        return parseFloat(total * 100);
    })

    //查询购物车数据
    const GetCartData = async () =>
    {
        //如果要是缓存中有购物车数据就不去请求了
        let cart = Object.getOwnPropertyNames(proxy.$cart.value).length > 0 ? proxy.$cart.value : [];

        if(cart.length > 0 && !cartids.value)
        {   
            CartList.value = cart
            return false
        }


        var params = {
            cartids: cartids.value,
            busid: business.value.id
        }

        let result = await proxy.$POST({url: '/cart/confirm', params})

        if(result.code == 0)
        {
            proxy.$fail({
                message: result.msg,
                onClose: () => proxy.$router.go(-1)
            })
            return false
        }

        CartList.value = result.data
        
        //转换规格信息
        CartList.value.map(item => {
            item.attrs = JSON.parse(item.attrs)
        })
    }

    //查询优惠券数据
    const GetCouponData = async () =>
    {
        var params = {
            busid: business.value.id
        }

        var result = await proxy.$POST({url: '/cart/coupon', params})

        if(result.code == 0) return false

        //可用的优惠券
        for(var item of result.data.CouponList)
        {
            CouponList.value.push({
                id:item.id,// 领取优惠券记录id
                name:item.coupon.title,// 优惠券名称
                startAt:item.coupon.createtime,// 优惠券开始时间
                endAt:item.coupon.endtime,// 优惠券结束时间
                rate: item.coupon.rate,// 折扣率
                valueDesc: `${item.coupon.rate*100}`,// 折扣券优惠金额文案
                unitDesc: '折',// 单位文案
                condition:item.coupon.status_text,// 满减条件
            })
        }

        // 不可用的优惠券
        for(let item of result.data.NotCouponList)
        {
            NotCouponList.value.push({
                id:item.id,// 领取优惠券记录id
                name:item.coupon.title,// 优惠券名称
                startAt:item.coupon.createtime,// 优惠券开始时间
                endAt:item.coupon.endtime,// 优惠券结束时间
                rate: item.coupon.rate,// 折扣率
                valueDesc: `${item.coupon.rate*100}`,// 折扣券优惠金额文案
                unitDesc: '折',// 单位文案
                condition:item.coupon.status_text,// 满减条件
            })
        }
    }

    //查询收货地址数据
    const GetAddressData = async () =>
    {
        var params = {
            busid: business.value.id
        }

        //如果客户有默认地址就返回默认地址，如果没有默认地址 随便返回一个地址
        var result = await proxy.$POST({url: '/cart/address', params})

        if(result.code == 0) return false

        address.value = {
            id:result.data.id,
            name:result.data.consignee,
            tel:result.data.mobile,
            region_text:result.data.region_text + result.data.address
        }
    }

    //添加收货地址
    const OnAddressAdd = async (values) =>
    {
        // 组装数据
        let params = {
            busid: business.value.id,
            consignee: values.name,
            address: values.addressDetail,
            mobile: values.tel,
            status: values.isDefault ? 1 : 0,
            code: values.areaCode,
            action:'confirm'
        }

        // 发送请求
        let result = await proxy.$POST({
            url: "/address/add",
            params
        })

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        AddressShow.value = false

        // 修改收货地址的信息
        address.value = {
            id:result.data.id,
            name:result.data.consignee,
            tel:result.data.mobile,
            region_text:result.data.region_text + result.data.address
        }
    }

    //查询收货地址列表
    const GetAddressList = async () => 
    {
        var result = await proxy.$POST({url: '/address/index', params: {busid: business.value.id}})

        if(result.code == 0) return proxy.$fail(result.msg)

        var temp = []

        for(var item of result.data)
        {
            if(item.status == '1') AddressActive.value = item.id

            temp.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                address: `${item.region_text} ${item.address}`,
                isDefault: item.status == '1' ? true : false
            })
        }
        
        AddressList.value = temp
    }

    //确认支付方式
    const OnPayConfirm = ({selectedOptions}) => 
    {
        //隐藏弹出层
        PayShow.value = false
        PayActive.value = selectedOptions[0]
    }

    //选择优惠券
    const OnCouponChange = (index) => 
    {
        //隐藏弹出层
        CouponShow.value = false

        // 设置选中的优惠券
        CouponActive.value = index
        
        if(index !== -1)
        {
            // 选中的优惠券
            let coupon = CouponList.value[index];

            // 优惠后总价
            let total = 0;

            // 计算商品的总价
            CartList.value.map(item => total += parseFloat(item.total));

            // 保留两位小数点
            total = total.toFixed(2);

            // 折扣率
            let rate = coupon.rate ? coupon.rate : 1;

            // 优惠后的总价
            let RatePrice = (parseFloat(total) * parseFloat(rate)).toFixed(2);

            let CouponPrice = (parseFloat(total) - parseFloat(RatePrice)).toFixed(2);

            CouponList.value[index].value = parseFloat(CouponPrice) * 100;
        }
    }

    //选择收货地址
    const OnAddressSelect = (item, index) =>
    {
        AddressSelect.value = false

        // 修改收货地址的信息
        address.value = {
            id:item.id,
            name:item.name,
            tel:item.tel,
            region_text:item.address
        }
    }

    //提交订单
    const OnSubmit = async () =>
    {
        proxy.$confirm({
            title: '确认提醒',
            message: '是否确认订单信息',
        }).then(async () => {

            //有购物车id 说明是从购物车过来的
            if(cartids.value)
            {
                //组装数据
                let params = {
                    busid:business.value.id,
                    cartids:cartids.value,
                    addrid:address.value.id,
                    pay:PayActive.value.value,
                    remark:remark.value
                }

                //判断是否有使用优惠券
                if(CouponActive.value !== -1)
                {
                    params.couponid = CouponList.value[CouponActive.value].id;
                }

                var result = await proxy.$POST({url: '/order/add', params})

                if(result.code == 0)
                {
                    proxy.$fail(result.msg)
                    return false
                }

                // 如果url存在，直接跳转订单详情
                if(result.url)
                {
                    proxy.$success({
                        message:result.msg,
                        onClose:() =>
                        {
                            proxy.$router.push({path:result.url,query:result.data,replace:true});
                        }
                    })
                }else
                {
                    //跳转到收银台界面
                    proxy.$router.push({path: '/business/cashier', query: {payid: result.data.id}})
                }
            }else
            {
                //从立即购买走过来的
                // 从CartList提取需要的数据
                let info = CartList.value[0];

                // 组装数据
                let params = {
                    busid:business.value.id,
                    addrid:address.value.id,
                    pay:PayActive.value.value,
                    remark:remark.value,
                    proid:info.proid,// 商品主键
                    price:info.price,// 商品价格
                    nums:info.nums,// 商品数量
                    attrs:info.attrs.length > 0 ? JSON.stringify(info.attrs) : '',// 已选择商品属性
                };

                // 是否使用优惠券
                if(CouponActive.value !== -1)
                {
                    params.couponid = CouponList.value[CouponActive.value].id;
                }

                let result = await proxy.$POST({
                    url:'/order/buy',
                    params
                })

                if(result.code == 0)
                {
                    proxy.$fail(result.msg);
                    return false
                }

                // 如果url存在，直接跳转订单详情
                if(result.url)
                {
                    proxy.$success({
                        message:result.msg,
                        onClose:() =>
                        {
                            proxy.$router.push({path:result.url,query:result.data,replace:true});
                        }
                    })
                }else
                {
                    // 跳转收银台
                    proxy.$router.push({path:'/business/cashier',query:{payid:result.data.id}});
                }
            }
            
        }).catch(err => {})
    }




</script>


<style scoped>
    .van-card{
        background-color:#fff;
    }

    :deep(.van-card__bottom){
        position: relative;
    }

    :deep(.van-card__num){
        position: absolute;
        bottom: 0px;
        right: 5px;
    }

    .title{
        font-size:14px;
        font-weight: bold;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        margin-bottom: 5px;
    }

    .tag{
        margin-right:5px;
    }

    .price{
        font-size:12px;
        font-weight: bold;
    }

    /* 姓名只一行显示，超出隐藏 */
    :deep(.van-contact-card__title) div:first-child{
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
    }
</style>